//
//  ZCTool.m
//  UniversalApp
//
//  Created by 凯朱 on 2019/5/30.
//  Copyright © 2019 徐阳. All rights reserved.
//

#import "ZCTool.h"
#import <Foundation/NSFileManager.h>
#import "SLLoadingView.h"
#import "SLShareAlertView.h"
#import <UserNotifications/UserNotifications.h>
#import "SLUnlockAlertView.h"
#import "Reachability.h"
static  NSUInteger const kDefaultViewTag = 999999999;
static  NSInteger const kHudTag = 17884553612;
@interface ZCTool()
@end

@implementation ZCTool
/**
 window上展示toast提示
 
 @param message 提示文案
 */
+(void)showToastOnKeyWindowWith:(NSString *)message{
    if (message.length == 0) return;
    //如果已经有toast弹窗了 暂时不立刻展示下一个弹窗
    UIView *messageView = [kAppWindow viewWithTag:540021];
    if (messageView){
        [messageView removeFromSuperview];
    }
    message = kLocalString(message);
    //展示toast提示
    CGSize size = STRING_SIZE_FONT(240, message, kFontMedium(16));
    messageView = [[UIView alloc] initWithFrame:CGRectMake(([[UIScreen mainScreen] bounds].size.width-(size.width+30))/2, (CGRectGetHeight(kAppWindow.bounds)-size.height-30)/2, size.width, size.height)];
    messageView.backgroundColor = KWhiteColor_text;
    messageView.tag = 540021;
    messageView.layer.cornerRadius = 20.0f;
    [messageView.layer setMasksToBounds:YES];
    [kAppWindow addSubview:messageView];
    
    //整个屏幕居中对齐
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, CGRectGetWidth(messageView.bounds), CGRectGetHeight(messageView.bounds))];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.tag = 1000;
    [titleLabel setText:message];
    
    [titleLabel setFont:kFontMedium(16)];
    [titleLabel setTextAlignment:NSTextAlignmentCenter];
    [titleLabel setTextColor:KColor_1];
    [titleLabel sizeToFit];
    titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    titleLabel.numberOfLines = 0;
    [messageView addSubview:titleLabel];
    
    //限制最长长度
    if (CGRectGetWidth(titleLabel.bounds)>270-30)
    {
        messageView.frame = CGRectMake(kScreenWidth/2-135,2*(KScreenHeight-size.height-30)/3-30,270,size.height+30);
    }
    else
    {
        messageView.frame = CGRectMake((kScreenWidth - CGRectGetWidth(titleLabel.bounds)-30)/2,2*(KScreenHeight-CGRectGetHeight(titleLabel.bounds)-30)/3-30,CGRectGetWidth(titleLabel.bounds)+30,CGRectGetHeight(titleLabel.bounds)+30);
    }
    
    titleLabel.frame = CGRectMake(15, 15, size.width, size.height);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.2 animations:^{
            messageView.alpha = 1;
        } completion:^(BOOL finished) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [UIView animateWithDuration:0.3 animations:^{
                    messageView.alpha = 0;
                } completion:^(BOOL finished) {
                    [messageView removeFromSuperview];
                }];
            });
        }];
    });
}

#pragma mark -
#pragma mark - ================<json转换相关>===============
/**
 字典转json字符串 - 无校验
 
 @param dic 字典
 @return json字符串
 */
+(NSString *)dictToJson:(NSDictionary *)dic
{
    if (dic == nil || ![dic isKindOfClass:[NSDictionary class]]) {
        return @"";
    }
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

/**
 数组转json字符串 - 无校验
 
 @param array 数组
 @return jsonStr
 */
+(NSString *)arrayToJson:(NSArray *)array
{
    if (array == nil || ![array isKindOfClass:[NSArray class]]) {
        return @"";
    }
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

/**
 字典或数组转字符串  代替方法  +(NSString *)systemUtilsDataToJson:(id)dicOrArr
 
 @param dicOrArr 字典或数组对象
 @return json字符串
 */
+(NSString *)objectToJson:(id)dicOrArr
{
    if ([dicOrArr isKindOfClass:[NSDictionary class]]) {
        return [self dictToJson:dicOrArr];
    }
    if ([dicOrArr isKindOfClass:[NSArray class]]) {
        return [self arrayToJson:dicOrArr];
    }
    
    return [NSString valueToString:dicOrArr];
}

/**
 json字符串转字典 - 有校验(解析失败或格式错误返回空字典)
 
 @param jsonStr json字符串
 @return 字典
 */
+(NSDictionary *)dictionaryWithJsonStr:(NSString *)jsonStr
{
    if ([jsonStr isKindOfClass:[NSDictionary class]]) return (NSDictionary *)jsonStr;
    
    if (jsonStr == nil || jsonStr.length == 0) return @{};
    
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    
    if(error) return @{};
    
    if ([dic isKindOfClass:[NSDictionary class]]) {
        return dic;
    }
    else{
        return @{};
    }
}

/**
 json字符串转数组 - 有校验(解析失败或格式错误返回空字典)
 
 @param jsonStr json字符串
 @return 数组
 */
+(NSArray *)arrayWithJsonStr:(NSString *)jsonStr
{
    if (![jsonStr isKindOfClass:[NSString class]]) {
        return @[];
    }
    if ([jsonStr isKindOfClass:[NSArray class]]) return (NSArray *)jsonStr;
    
    if (jsonStr == nil || jsonStr.length == 0) return @[];
    
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    
    if(error) return @[];
    
    if ([array isKindOfClass:[NSArray class]]) {
        return array;
    }
    else{
        return @[];
    }
}

/**
 处理图片并且保存资源到本地 - 保存的为相对路径
 
 @param image 图片
 @return 图片文件名 - 相对路径
 */
+(NSString *)saveImageToLocalWithImage:(UIImage *)image{
    
    //压缩图片
    NSData *imageData = [self compressOriginalImage:image toMaxDataSizeKBytes:1024*1024];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:kDocImageName];
    NSString *time = [formatter stringFromDate:[NSDate date]];
    
    //本地图片完整路径
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", time];
    NSString *fullPath = [NSString stringWithFormat:@"%@/%@", kFileCacheDirectory, fileName];
    
    //创建文件夹
    if (![self creatFileDirectoryWith:kFileCacheDirectory]) {
        //文件夹创建失败
        return @"";
    }
    //写入文件
    BOOL isSuccess = [[NSFileManager defaultManager] createFileAtPath:fullPath contents:imageData attributes:nil];
    
    //写入文件成功
    if (isSuccess) {
        return fileName;
    }
    //失败返回空字符串
    return @"";
}

+(NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length <= size) {
        return data;
    }
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < size) {
            min = compression;
        } else if (data.length > size * 0.9) {
            max = compression;
        } else {
            break;
        }
    }
    return data;
}

/**
 获取完整的文件路径名 - 绝对路径
 
 @param fileName 文件名
 */
+(NSString *)getFullFilePathWithFileName:(NSString *)fileName{
    //已经是完整的路径名
    if ([kSTRING(fileName) containsString:@"kFileCacheDirectory"]){
        return kSTRING(fileName);
    }
    //不完整的 - 拼接完整的
    NSString *fullPath = [NSString stringWithFormat:@"%@/%@",kFileCacheDirectory,fileName];
    return fullPath;
}

/**
 在指定目录下创建一个文件夹
 
 @param dirPath 文件夹路径
 */
+(BOOL)creatFileDirectoryWith:(NSString *)dirPath{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // fileExistsAtPath 判断一个文件或目录是否有效，isDirectory判断是否一个目录
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:dirPath isDirectory:&isDir];
    //如果文件夹不存在
    if (!(isDir == YES && existed == YES)){
        BOOL creatSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
        return creatSuccess;
    }
    //如果存在直接返回YES
    return YES;
}

/**
 解决拍照之后照片自动旋转90度wen
 
 @param image 图片
 @return 修复之后的图片
 */
+(UIImage *)fixOrientation:(UIImage *)image
{
    if (image.imageOrientation == UIImageOrientationUp) return image;
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (image.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, image.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }
    
    switch (image.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }
    
    CGContextRef ctx = CGBitmapContextCreate(NULL, image.size.width, image.size.height,
                                             CGImageGetBitsPerComponent(image.CGImage), 0,
                                             CGImageGetColorSpace(image.CGImage),
                                             CGImageGetBitmapInfo(image.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (image.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.height,image.size.width), image.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.width,image.size.height), image.CGImage);
            break;
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

static  NSString *const kHodTtileStr = @"正在努力加载中...";
/**
 window上菊花
 */
+(void)showHudOnKeyWindow
{
    dispatch_main_async_safe(^{
        MBProgressHUD *hod = [kAppWindow viewWithTag:kHudTag];
        if (!hod){
            hod =  [MBProgressHUD showHUDAddedTo:kAppWindow animated:YES];
        }
        hod.detailsLabel.text = kHodTtileStr;
        hod.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
//        hod.backgroundView.color = [UIColor colorWithWhite:0.f alpha:.2f];
        hod.backgroundView.color = kHexColor(@"#262626");

    });
}

/**
 window上菊花 自定义文案
 */
+(MBProgressHUD *)showHudOnKeyWindowWith:(NSString *)message{
    __block NSString *messageStr = @"";
    __block MBProgressHUD *hod = nil;
    dispatch_main_async_safe(^{
        hod = [kAppWindow viewWithTag:kHudTag];
        if (!hod){
            hod =  [MBProgressHUD showHUDAddedTo:kAppWindow animated:YES];
            hod.tag = kHudTag;
        }
        messageStr = message.length > 0 ? message : kHodTtileStr;
        hod.detailsLabel.text = messageStr;
        hod.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
        hod.backgroundView.color = [UIColor colorWithWhite:0.f alpha:.2f];
    });
    return hod;
}

/**
 隐藏window上菊花
 */
+(void)hideHudOnKeyWindow
{
    dispatch_main_async_safe(^{
        [MBProgressHUD hideHUDForView:kAppWindow animated:YES];
    });
}

/**
 默认菊花
 
 @param view - 父视图
 */
+(void)showHudOnView:(UIView *)view
{
    dispatch_main_async_safe(^{
        MBProgressHUD *hod = [view viewWithTag:kHudTag];
        if (hod) return;
        hod = [MBProgressHUD showHUDAddedTo:view animated:YES];
        hod.tag = kHudTag;
        hod.detailsLabel.text = kHodTtileStr;
    });
}

/**
 自定义文案菊花
 
 @param view - 父视图
 @param message - 文案
 */
+(MBProgressHUD *)showHudOnView:(UIView *)view message:(NSString *)message{
    __block NSString *messageStr = @"";
    __block MBProgressHUD *hod = nil;
    dispatch_main_async_safe(^{
        if (!hod){
            hod =  [MBProgressHUD showHUDAddedTo:view animated:YES];
        }
        messageStr = message.length > 0 ? message : kHodTtileStr;
        hod.detailsLabel.text = messageStr;
    });
    return hod;
}

+(void)hideHudOnView:(UIView *)view
{
    [MBProgressHUD hideHUDForView:view animated:YES];
}

/**
 默认文案缺省图
 
 @param view 父视图
 */
+(void)showDefaultImageOnView:(UIView *)view
{
    [self showDefaultImageOnView:view message:@"No data"];
}

+(BOOL)isFullScreenIphone {
    BOOL isFullIphone = NO;
    if (@available(iOS 11.0, *)) {
        UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
        if (mainWindow.safeAreaInsets.bottom > 0.0) {
            isFullIphone = YES;
        }
    }
    
    return isFullIphone;
}

/**
 隐藏缺省图
 
 @param view 父视图
 */
+(void)hideDefaultImageOnView:(UIView *)view{
    UIView *defaultView = [view viewWithTag:kDefaultViewTag];
    if (defaultView) {
        [defaultView removeFromSuperview];
        defaultView = nil;
    }
}

/**
 默认图 文案自定义
 
 @param view - 父视图
 @param message - 文案
 */
+(void)showDefaultImageOnView:(UIView *)view message:(NSString *)message
{
    if ([view viewWithTag:kDefaultViewTag]) {
        return;
    }
    NSString *imageUrl = [NSString stringWithFormat:@"no_data"];
    UIImage *image = [UIImage imageNamed:imageUrl];
    UIView *defaultView = [[UIView alloc] initWithFrame:view.bounds];
    defaultView.tag =  kDefaultViewTag;
    UIView *iconView = [[UIView alloc] init];
    defaultView.backgroundColor = view.backgroundColor;
    UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, image.size.width, image.size.height)];
    
    [iconImageView setImage:image];
    [view addSubview:defaultView];
    [defaultView addSubview:iconView];
    [iconView addSubview:iconImageView];
    
    //提示
    UILabel *titleLabel = [[UILabel alloc] init];
    [titleLabel setText:kSTRING(message)];
    [titleLabel setFont:kFont(16)];
    [titleLabel setTextColor:KColor_3];
    [titleLabel sizeToFit];
    [iconView addSubview:titleLabel];
    [titleLabel setTextAlignment:NSTextAlignmentCenter];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(defaultView.mas_centerX);
        make.top.equalTo(iconImageView.mas_bottom).offset(40);
    }];
    CGFloat width = iconImageView.width;
    CGFloat height  = iconImageView.height + 40 + titleLabel.height;
    defaultView.frame = CGRectMake((defaultView.width-width)/2, (defaultView.height-height)/2-50, width, height);
}

+(UIImage *)getBgImage{
    NSString *filPath = [[NSUserDefaults standardUserDefaults] objectForKey:@"zkBgImgTag"];
    if (kSTRING(filPath).length == 0) {
        return nil;
    }
    NSString *imageUrl = [NSString stringWithFormat:@"%@/%@",kFileCacheDirectory,filPath];
    UIImage *localImage = [UIImage imageWithContentsOfFile:imageUrl];
    return localImage;
}

+(UIImage *)getJudgBgImage{
    NSString *filPath = [[NSUserDefaults standardUserDefaults] objectForKey:@"zkJudgBgImgTag"];
    if (kSTRING(filPath).length == 0) {
        return nil;
    }
    NSString *imageUrl = [NSString stringWithFormat:@"%@/%@",kFileCacheDirectory,filPath];
    UIImage *localImage = [UIImage imageWithContentsOfFile:imageUrl];
    return localImage;
}

+(UIImage *)getScoreBgImage{
    NSString *filPath = [[NSUserDefaults standardUserDefaults] objectForKey:@"zkScoreBgImgTag"];
    if (kSTRING(filPath).length == 0) {
        return nil;
    }
    NSString *imageUrl = [NSString stringWithFormat:@"%@/%@",kFileCacheDirectory,filPath];
    UIImage *localImage = [UIImage imageWithContentsOfFile:imageUrl];
    return localImage;
}

//截屏并且保存到相册
+(void)screenShotsAndSaveComplete:(void(^)(UIImage * img)) complete{
    
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        kShowToast(@"Please enable album permissions first");
        if(complete){
            complete(nil);
        }
        return;
    }
    
    if (status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status != PHAuthorizationStatusAuthorized) {
                kShowToast(@"Please enable album permissions first");
                if(complete){
                    complete(nil);
                }
                return;
            }
        }];
    }
    
    CGSize imageSize = [[UIScreen mainScreen] bounds].size;
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow * window in [[UIApplication sharedApplication] windows]) {
        if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen]) {
            CGContextSaveGState(context);

            CGContextTranslateCTM(context, [window center].x, [window center].y);

            CGContextConcatCTM(context, [window transform]);

            CGContextTranslateCTM(context, -[window bounds].size.width*[[window layer] anchorPoint].x, -[window bounds].size.height*[[window layer] anchorPoint].y);

            [[window layer] renderInContext:context];

            CGContextRestoreGState(context);
        }
    }

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
    NSLog(@"Suceeded!");

    if(complete){
        complete(image);
    }
}

//只截屏
+(void)screenShotsComplete:(void(^)(UIImage * img)) complete{
    CGSize imageSize = [[UIScreen mainScreen] bounds].size;
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow * window in [[UIApplication sharedApplication] windows]) {
        if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen]) {
            CGContextSaveGState(context);

            CGContextTranslateCTM(context, [window center].x, [window center].y);

            CGContextConcatCTM(context, [window transform]);

            CGContextTranslateCTM(context, -[window bounds].size.width*[[window layer] anchorPoint].x, -[window bounds].size.height*[[window layer] anchorPoint].y);

            [[window layer] renderInContext:context];

            CGContextRestoreGState(context);
        }
    }

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"Suceeded!");

    if(complete){
        complete(image);
    }
}

//调用系统分享当前截图
+(void)shareWithTitle:(NSString *)title vc:(UIViewController *)vc{
    
    NSString *testToShare = title;
    [ZCTool screenShotsComplete:^(UIImage * _Nonnull img) {
        UIImage *imageToShare = img;
        NSArray *activityItems = @[testToShare,imageToShare];
        UIActivityViewController *activityVc = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
        [vc presentViewController:activityVc animated:YES completion:nil];
        activityVc.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
            if (completed) {
                NSLog(@"分享成功");
            }else{
                NSLog(@"分享取消");
            }
        };
    }];
}

/**
 获取当前视图的VC层
 
 @return
 */
+(UIViewController *)getCurrentUIVC
{
    UIViewController  *superVC = [self seg_getCurrentVC];
    
    if ([superVC isKindOfClass:[UITabBarController class]]) {
        
        UIViewController  *tabSelectVC = ((UITabBarController*)superVC).selectedViewController;
        
        if ([tabSelectVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)tabSelectVC).viewControllers.lastObject;
        }
        return tabSelectVC;
    }else
        if ([superVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)superVC).viewControllers.lastObject;
        }
    return superVC;
    
}

+(UIViewController *)seg_getCurrentVC{
    
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    if ([window subviews].count > 0) {
        UIView *frontView = [[window subviews] objectAtIndex:0];
        id nextResponder = [frontView nextResponder];
        
        if ([nextResponder isKindOfClass:[UIViewController class]])
            result = nextResponder;
        else{
            result = window.rootViewController;
        }
    }
    return result;
}

+(NSString *)locaStrWith:(NSString *)str{
    NSString *curLang = [[NSUserDefaults standardUserDefaults] valueForKey:@"curLang"];
    if (kSTRING(curLang).length == 0) curLang = @"en";
    NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:curLang ofType:@"lproj"]];
    NSString *localStr = NSLocalizedStringFromTableInBundle(str, @"Localizable", bundle, nil);
    if (kSTRING(localStr).length == 0) {
        return str;
    }
    return localStr;
}

+(NSString *)getLang{
    NSString *curLang = [[NSUserDefaults standardUserDefaults] valueForKey:@"curLang"];
    if (kSTRING(curLang).length == 0) curLang = @"en";
    return curLang;
}


//调用系统分享文件
+(void)shareWithTitle:(NSString *)title filePath:(NSString *)filePath vc:(UIViewController *)vc{
    NSString *testToShare = title;
    NSArray *activityItems = @[testToShare,[NSURL fileURLWithPath:filePath]];
    UIActivityViewController *activityVc = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    [vc presentViewController:activityVc animated:YES completion:nil];
    activityVc.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            NSLog(@"分享成功");
        }else{
            NSLog(@"分享取消");
        }
    };
}

//调用系统分享url
+(void)shareWithTitle:(NSString *)title httpUrl:(NSString *)httpUrl vc:(UIViewController *)vc{
    NSString *testToShare = title;
    NSArray *activityItems = @[testToShare,[NSURL URLWithString:httpUrl]];
    UIActivityViewController *activityVc = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    [vc presentViewController:activityVc animated:YES completion:nil];
    activityVc.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            NSLog(@"分享成功");
        }else{
            NSLog(@"分享取消");
        }
    };
}

+(void)showLoadingWith:(NSString *)message view:(UIView *)view{
    SLLoadingView *loadingV = [view viewWithTag:1008899];
    if (loadingV) {
        [loadingV removeFromSuperview];
    }
    SLLoadingView *loadingView = [SLLoadingView viewFromXIB];
    loadingView.textLbl.text = kSTRING(message);
    [view addSubview:loadingView];
    [loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    loadingView.tag = 1008899;
    [view bringSubviewToFront:loadingView];
}

+(void)hideLoading:(UIView *)view{
    SLLoadingView *loadingV = [view viewWithTag:1008899];
    if (loadingV) {
        [loadingV removeFromSuperview];
    }
}
+(void)showLoadingOnKeyWindow{
    [self showLoadingOnKeyWindowWith:@""];
}

+(void)showLoadingOnKeyWindowWith:(NSString *)message{
    [self showLoadingWith:message view:kAppWindow];
}

+(void)hideLoadingOnKeyWindow{
    [self hideLoading:kAppWindow];
}

+(void)showLoadingOnKeyWindowWith:(NSString *)message hideTime:(NSInteger)hideTime{
    [self showLoadingWith:message view:kAppWindow];
    if (hideTime && hideTime > 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(hideTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self hideLoading:kAppWindow];
        });
    }
}

+(void)updateLoadingOnKeyWindowWith:(NSString *)message{
    SLLoadingView *loadingV = [kAppWindow viewWithTag:1008899];
    if (loadingV) {
        loadingV.textLbl.text = kSTRING(message);
    }
}

//自动连接上设备
+(void)connectDeviceWith:(SLLockModel *)model toast:(NSString *)toast finish:(void(^)(BOOL isSuccess))finish{
    if ([kSTRING(model.deviceCategory) isEqualToString:@"1"]) {
        
        //已经连上该设备
        if (kCurDevice && [kCurDevice.deviceNo isEqualToString:model.deviceNo]) {
            NSLog(@"当前已连接设备 %@,%@",model.deviceNo,[SLBluetoothManager sharedManager].curPeripheral);
            if (finish) finish(YES);
            return;
        }else{
            NSLog(@"断开连接 %@",kSTRING(kCurDevice.deviceNo));
            [[SLBluetoothManager sharedManager] disConnectPeripheral];
        }
        
        //开启了节能模式
        if (model.isOpenEnergyModel) {
            [self showAwakeTipAlert:^{
                [self connectDeviceAready:model toast:toast finish:finish];
            }];
        }else{
            [self connectDeviceAready:model toast:toast finish:finish];
        }
    }else{
        if (finish) finish(YES);
    }
}

+(void)connectDeviceAready:(SLLockModel *)model toast:(NSString *)toast finish:(void(^)(BOOL isSuccess))finish{
    //未连接 - 去连接
    if (toast.length > 0) [ZCTool showLoadingOnKeyWindowWith:toast];
    [[SLBluetoothManager sharedManager] startSearchDeviceAndConnect:model.deviceNo isBridge:NO finish:^(BOOL isSuccess, CBPeripheral *peripheral,id data, NSString *errorMsg) {
        if (toast.length > 0) [ZCTool hideLoadingOnKeyWindow];
        if (isSuccess) {
            kCurDevice = model;
            if (finish) finish(YES);
        }else{
            kCurDevice = nil;
            kShowToast(@"Connect faild");
            if (finish) finish(NO);
        }
    }];
}

+(BOOL)isOpenDebugModel{
//#ifdef DEBUG
    NSString *model = kSTRING([[NSUserDefaults standardUserDefaults] objectForKey:@"openDebugModel"]);
    if ([model isEqualToString:@"1"]) {
        return YES;
    }
    return NO;
//#endif
//    return NO;
}

+(void)showAwakeTipAlert:(void(^)(void))click{
    __weak SLSuccessAlertView *alert = [SLSuccessAlertView viewFromXIB];
    alert.topLbl.text = kLocalString(@"Awake padlock");
    alert.contentLbl.text = kLocalString(@"Touch the fingerprint pad to awake the padlock. Or switch off 'Energy saving mode' to keep the padlock awake at all times.");
//    alert.contentLbl.font = kFont(16);
    alert.icon.image = [UIImage imageNamed:@"icon_touch"];
    [alert setBtnTitle:kLocalString(@"Done")];
    [alert updateHeight];
    [alert setBtnBlock:^(NSInteger btnIndex) {
        [alert removeFromSuperview];
        if (click) click();
    }];
    [kAppWindow addSubview:alert];
}

//自动连接上设备 - 后台进行无感知
+(void)connectDeviceBackgroundWith:(SLLockModel *)model finish:(void(^)(BOOL isSuccess))finish{
    if ([kSTRING(model.deviceCategory) isEqualToString:@"1"]) {
        //已经连上该设备了
        if (kCurDevice && [kCurDevice.deviceNo isEqualToString:model.deviceNo]) {
            if (finish) finish(YES);
            return;
        }else{
            [[SLBluetoothManager sharedManager] disConnectPeripheral];
        }
        //未连接 - 去连接
        [[SLBluetoothManager sharedManager] startSearchDeviceAndConnect:model.deviceNo isBridge:NO finish:^(BOOL isSuccess, CBPeripheral *peripheral,id data, NSString *errorMsg) {
            if (isSuccess) {
                kCurDevice = model;
                if (finish) finish(YES);
            }else{
                kCurDevice = nil;
                if (finish) finish(NO);
            }
        }];
    }else{
        if (finish) finish(YES);
    }
}

//批量同步开锁日志数据
+(void)batchSyncDeviceOpenLogDatas:(void(^)(BOOL isSuccess,NSString *message))finish{
    //开始同步数据
    [[SLBluetoothManager sharedManager] getDeviceOpenLogDataWith:^(NSArray <SLLockLogModel *>*logData) {
        //有数据，同步给服务器
        if (logData.count == 0) {
            if (finish) finish(NO,kLocalString(@"Update logs finish"));
            return;
        }
        NSMutableArray *mslUnlockLogList = [NSMutableArray new];
        [logData enumerateObjectsUsingBlock:^(SLLockLogModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
            if (model.unlockTime.length == 10) {
                NSDictionary *openInfo = @{@"unlockType":kSTRING(model.unlockType),
                                           @"unlockTime":kSTRING(model.unlockTime),
                                           @"accessId":kSTRING(model.accessId),
                                           @"unlockUid":model.unlockUid,
                                           @"deviceId":kCurClickDevice.deviceId};
                [mslUnlockLogList addObject:openInfo];
            }
        }];
        
        NSDictionary *params = @{@"mslUnlockLogList":mslUnlockLogList,
                                 @"deviceId":kCurClickDevice.deviceId};
        [ZKHttpManager postWithPath:@"/msl_lock_key/SyncInfo" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            if (finish) finish(isSuccessed,message);
        }];
       
    }];
}

//批量同步钥匙数据
+(void)batchSyncDeviceKeyDatas:(void(^)(BOOL isSuccess,NSString *message))finish{
    [[SLBluetoothManager sharedManager] getFingerAccessDataWith:@"" finish:^(BOOL isSuccess, NSArray<SLLockKeyModel *> *keyDatas) {
        if (keyDatas.count == 0) {
            NSDictionary *params = @{@"mslLockKeyDtoList":@[],
                                     @"deviceId":kCurClickDevice.deviceId};
            [ZKHttpManager postWithPath:@"/msl_lock_key/SyncInfo" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
                if (finish) finish(isSuccessed,message);
            }];
            return;
        }
        // 解析出一个成员下的多个指纹信息
        // 先根据成员id分组
        NSMutableDictionary<NSString *, NSMutableArray<SLLockKeyModel *> *> *uidDictionary = [NSMutableDictionary new];
        [keyDatas enumerateObjectsUsingBlock:^(SLLockKeyModel *keyModel, NSUInteger idx, BOOL * _Nonnull stop) {
            // 获取 uid
            NSString *uid = keyModel.uid;
            if (!uidDictionary[uid]) {
                uidDictionary[uid] = [NSMutableArray new];
            }
            [uidDictionary[uid] addObject:keyModel];
        }];
      
        //分组拼接参数
        NSMutableArray *mslLockKeyDtoList = [NSMutableArray new];
        NSArray *uidKeys = [uidDictionary allValues];
        [uidKeys enumerateObjectsUsingBlock:^(NSMutableArray<SLLockKeyModel *> *keyModels, NSUInteger idx, BOOL * _Nonnull stop) {
            NSMutableArray *fingers = [NSMutableArray new];
            NSMutableDictionary *keysInfo = [[NSMutableDictionary alloc] init];
            SLLockKeyModel *keyModel = keyModels[0];
            [keysInfo setObject:kSTRING(@(keyModel.keyType)) forKey:@"keyType"];
            [keysInfo setObject:kSTRING(@(keyModel.lockType)) forKey:@"lockType"];
            [keysInfo setObject:kSTRING(keyModel.startTime) forKey:@"startTime"];
            [keysInfo setObject:kSTRING(keyModel.endTime) forKey:@"endTime"];
            [keysInfo setObject:[ZCTool objectToJson:keyModel.weekDays] forKey:@"weekDays"];
            [keysInfo setObject:kSTRING(keyModel.dayStart) forKey:@"dayStart"];
            [keysInfo setObject:kSTRING(keyModel.dayEnd) forKey:@"dayEnd"];
            [keysInfo setObject:kSTRING(keyModel.uid) forKey:@"uid"];
            [keysInfo setObject:kSTRING(kCurClickDevice.deviceId) forKey:@"deviceId"];
            [keysInfo setObject:kSTRING(keyModel.isUsbKey) forKey:@"isUsbKey"];
            [keysInfo setObject:kSTRING(keyModel.isUse) forKey:@"isUse"];
            
            [keyModels enumerateObjectsUsingBlock:^(SLLockKeyModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
                SLLockFingerModel *fingerModel = model.fingers[0];
                NSMutableDictionary *fingerInfo = [[NSMutableDictionary alloc] init];
                [fingerInfo setObject:kSTRING(fingerModel.accessId) forKey:@"accessId"];
                [fingerInfo setObject:kSTRING(fingerModel.uid) forKey:@"uid"];
                [fingers addObject:fingerInfo];
            }];
            [keysInfo setObject:fingers forKey:@"mslLockFingList"];
            
            [mslLockKeyDtoList addObject:keysInfo];
        }];
//        NSLog(@"同步钥匙信息:%@",mslLockKeyDtoList);
        NSDictionary *params = @{@"mslLockKeyDtoList":mslLockKeyDtoList,
                                 @"deviceId":kCurClickDevice.deviceId};
        [ZKHttpManager postWithPath:@"/msl_lock_key/SyncInfo" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            if (finish) finish(isSuccessed,message);
        }];
        
    }];
}


+(NSString *)updateTimeWith:(NSString *)sysncTime{
    if (kSTRING(sysncTime).length == 0) {
        return @"";
    }
    NSInteger now = [[[NSDate date] timestamp] integerValue];
    NSInteger time = now - [sysncTime integerValue];
    if (time < 60) {
        return kLocalString(@"Last synced just now.");
    }
    NSString *descStr = kLocalString(@"Last synced <1> ago.");
    NSString *timeStr = [self configTimeStrWith:time];
    descStr =  [descStr stringByReplacingOccurrencesOfString:@"<1>" withString:timeStr];
    return descStr;
}

+(NSString *)configTimeStrWith:(NSInteger)time{
    long day = time / (3600 * 24);
    long hour = time % (3600 * 24)/3600;
    long min = time % 3600/60;
    long seconds = time;
    NSString *dayStr = @"";
    NSString *hourstr = @"";
    NSString *minstr = @"";
    NSString *secondStr = @"";
    if (day > 0){
        dayStr = [NSString stringWithFormat:@"%lu %@",day,kLocalString(@"day")];
        return dayStr;
    }
    
    if (hour > 0) {
        hourstr = [NSString stringWithFormat:@"%lu %@",hour,kLocalString(@"hour")];
        return hourstr;
    }
    
    if (min > 0) {
        minstr = [NSString stringWithFormat:@"%lu %@",min,kLocalString(@"min")];
        return minstr;
    }
    
    if (seconds > 0) {
        secondStr = [NSString stringWithFormat:@"%lu %@",seconds,kLocalString(@"seconds")];
    }
    return secondStr;
}

+(NSString *)commonDateFormart{
    return @"HH:mm MMM. d";
}

+(NSString *)getCurDateStr{
    NSString *time = [NSString timeStringFromTimestamp:[[NSDate date] timestamp] formart:kCommonDateFormart];
    return time;
}

+(NSString *)getDateStrWith:(NSString *)timeInterval{
    NSString *time = [NSString timeStringFromTimestamp:timeInterval formart:kCommonDateFormart];
    return time;
}

//添加蓝牙钥匙
+(void)uploadBlueToothKeyData:(SLLockKeyModel *)keyModel{
    [ZCTool showLoadingOnKeyWindow];
    NSDictionary *params = @{@"keyType":kSTRING(@(keyModel.keyType)),
                             @"keyName":keyModel.keyName,
                             @"uid":kSTRING(keyModel.uid),
                             @"lockType":kSTRING(@(keyModel.lockType)),
                             @"startTime":keyModel.startTime,
                             @"endTime":keyModel.endTime,
                             @"weekDays":[ZCTool objectToJson:keyModel.weekDays],
                             @"dayStart":keyModel.dayStart,
                             @"dayEnd":keyModel.dayEnd,
                             @"deviceId":kCurClickDevice.deviceId};
    [ZKHttpManager postWithPath:@"/msl_lock_key/add" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccessed) {
            kShowToast(message);
            return;
        }
        keyModel.keyId = kSTRING(result[@"result"][@"keyId"]);
        kShowToast(@"Add access Success!");
        kNotifyRefreshDevcieList;
        UIViewController *vc = [UIViewController viewControllerWithClassName:@"SLAccessManagerVC"];
        if (vc) {
            [[ZCTool getCurrentUIVC].navigationController popToViewController:vc animated:YES];
        }else{
            [[ZCTool getCurrentUIVC].navigationController popToRootViewControllerAnimated:YES];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kAddAccessSuccess" object:@{@"model":keyModel}];
    }];
}

+(void)showShareAlertView:(NSString *)keyId{
    if (keyId.length == 0) return;
    
    SLShareAlertView *alertView = [SLShareAlertView viewFromXIB];
    NSString *timeStr = [[NSDate date] timestamp];
    alertView.linkLbl.text = [NSString stringWithFormat:@"%@/#/appshare/%@/%@/%@",URL_web,keyId,kUserInfo.userId,timeStr];
    [alertView showWithAnmation:[self getCurrentUIVC].view];
    alertView.tag = 100;
    kWeakSelf(self);
    [alertView setBtnBlock:^(NSInteger btnIndex) {
        [weakself handleShareViewAction:btnIndex];
    }];
}

+(void)handleShareViewAction:(NSInteger )index{
    UIViewController *vc = [self getCurrentUIVC];
    SLShareAlertView *alertView = [vc.view viewWithTag:100];
    if (index == 1) {//去分享
        NSString *message = [NSString stringWithFormat:@"%@ %@",kLocalString(@"You have received HEXFORCE Bluetooth Key from"),kUserInfo.nickName];
        [ZCTool shareWithTitle:message httpUrl:alertView.linkLbl.text vc:vc];
    }else if (index == 2){//跳过
        [UIView animateWithDuration:0.25 animations:^{
            alertView.mj_y = kScreenHeight;
        } completion:^(BOOL finished) {
            [alertView removeFromSuperview];
        }];
    }
}

// 检查开锁时间
+(BOOL)checkGuestTime{
    SLLockModel *model = kCurClickDevice;
    BOOL result = NO;
    if (model.keyType == 1) {
        result = YES;
    } else if (model.keyType == 2 || model.keyType == 3) {
        NSDate *start = [NSDate dateWithString:model.startTime formatString:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *end = [NSDate dateWithString:model.endTime formatString:@"yyyy-MM-dd HH:mm:ss"];
        //时间段钥匙还要判断是否在循环天内
        if (model.keyType == 2) {
            NSArray *weekDays = [ZCTool arrayWithJsonStr:model.weekDays];
            if (weekDays.count == 0) {
                result = [[NSDate date] isBetweenStartTime:start endTime:end];
            } else {
                result = [self isTodayInWeekdays:weekDays] && [[NSDate date] isBetweenStartTime:start endTime:end];
            }
        } else {
            result = [[NSDate date] isBetweenStartTime:start endTime:end];
        }
    }
    return result;
}

+(BOOL)isTodayInWeekdays:(NSArray<NSString *> *)weekdays {
    // 获取当前日期
    NSDate *currentDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 获取当前星期几（0=星期日, 1=星期一, ..., 6=星期六）
    NSDateComponents *components = [calendar components:NSCalendarUnitWeekday fromDate:currentDate];
    NSInteger weekday = components.weekday - 1; // 转换为 0-6
    // 检查当前星期几是否在给定的 weekdays 数组中
    return [weekdays containsObject:kSTRING(@(weekday))];
}

//固件版本升级检测
+(void)checkUpdateInfo:(NSString *)curFirmVersion finish:(void(^)(BOOL needUpdate, id updateInfo))finish{
    if (curFirmVersion.length == 0) {
        if (finish) finish(NO,nil);
        return;
    }
    //获取固件升级信息
    NSString *url = [NSString stringWithFormat:@"/msl_user/GetFirmwareUpgradeList/%@",kCurClickDevice.deviceNo];
    [ZKHttpManager getWithPath:url params:nil finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        if (!isSuccessed) {
            if (finish) finish(NO,nil);
            return;
        }
        //获取下载地址
        NSArray *list = result[@"result"];
        if (![list isKindOfClass:[NSArray class]] || list.count == 0) {
            if (finish) finish(NO,nil);
            return;
        }
        NSDictionary *info = list[0];
        NSString *firmwareId = kSTRING(info[@"firmwareId"]);
        NSString *taskId = kSTRING(info[@"taskId"]);
        if (firmwareId.length == 0) {
            if (finish) finish(NO,nil);
            return;
        }
        NSString *url2 = [NSString stringWithFormat:@"/msl_user/GetFirmwareById/%@",firmwareId];
        [ZKHttpManager getWithPath:url2 params:nil finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            if (!isSuccessed) {
                if (finish) finish(NO,nil);
                return;
            }
            NSDictionary *data = result[@"result"];
            NSString *swVerNumber = kSTRING(data[@"softwareVersion"]);
            NSString *serverVerNumber = [[swVerNumber lowercaseString] componentsSeparatedByString:@"v"].lastObject;
            NSString *curVerNumber = [[curFirmVersion lowercaseString] componentsSeparatedByString:@"v"].lastObject;
            if (swVerNumber.length == 0 || curVerNumber.length == 0) {
                if (finish) finish(NO,nil);
                return;
            }
            NSComparisonResult compareResult = [self compareVersion:curVerNumber withVersion:serverVerNumber];
            if (compareResult == NSOrderedAscending) {
                NSMutableDictionary *updateInfo = [[NSMutableDictionary alloc] initWithDictionary:data];
                [updateInfo setObject:curVerNumber forKey:@"curVersion"];
                [updateInfo setObject:serverVerNumber forKey:@"serverVersion"];
                [updateInfo setObject:taskId forKey:@"taskId"];
                if (finish) finish(YES,updateInfo);
            }else{
                if (finish) finish(NO,nil);
            }
        }];
    }];
    
}

+(NSComparisonResult)compareVersion:(NSString *)version1 withVersion:(NSString *)version2{
    NSArray *components1 = [version1 componentsSeparatedByString:@"."];
    NSArray *components2 = [version2 componentsSeparatedByString:@"."];
    
    NSInteger count = MAX(components1.count, components2.count);
    
    for (NSInteger i = 0; i < count; i++) {
        NSInteger number1 = (i < components1.count) ? [components1[i] integerValue] : 0;
        NSInteger number2 = (i < components2.count) ? [components2[i] integerValue] : 0;
        
        if (number1 < number2) {
            return NSOrderedAscending;
        } else if (number1 > number2) {
            return NSOrderedDescending;
        }
    }
    
    return NSOrderedSame;
}

/*
 网络检查
 
 @return YES-有网络 NO-无网络
 */
+(BOOL)checkNetWork{
    
    BOOL isHaveNet = YES;
    Reachability *r = [Reachability reachabilityWithHostName:URL_main];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:{
            isHaveNet = NO;
            break;
        }
        case ReachableViaWiFi: case ReachableViaWWAN:{
            isHaveNet = YES;
            break;
        }
        default:{
            break;
        }
    }
    return isHaveNet;
}


+(void)getFileSizeWidthUrl:(NSString *)url finish:(void(^)(NSString *size))finish{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:@{} progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
    }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSDictionary *dic = [(NSHTTPURLResponse *)task.response allHeaderFields];
        CGFloat length = [[dic objectForKey:@"Content-Length"] floatValue];// Content-Length单位是byte，除以1024后是KB
        NSString *size;
        if (length >= 1048576) {//1048576bt = 1M  小于1m的显示KB 大于1m显示M
            size = [NSString stringWithFormat:@"%.2fM",length/1024/1024];
        }else{
            size = [NSString stringWithFormat:@"%.1fKB",length/1024];
        }
        if (finish) {
            finish(size);
        }
    }];
}

+(NSString *)temperatureWith:(NSString *)level{
    NSString *curTempUnit = kSTRING([[NSUserDefaults standardUserDefaults] objectForKey:@"curTempUnit"]);
    NSString *unitStr = [curTempUnit isEqualToString:@"F"] ? @"°F" : @"°C";
    if ([unitStr isEqualToString:@"°F"]) {
        NSInteger temperature = ([level integerValue] * 9.0 / 5.0) + 32;
        return [NSString stringWithFormat:@"%ld%@",temperature,unitStr];
    }else{
        return [NSString stringWithFormat:@"%@%@",level,unitStr];
    }
}


+(void)showLocalNotfyAlertWith:(NSString *)title body:(NSString *)body{
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

    // 创建通知内容
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = title;
    content.body = body;
    content.sound = [UNNotificationSound defaultSound];

    // 设置触发条件（例如，延迟 5 秒后触发）
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:NO];

    // 创建通知请求
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"LocalNotification"
                                                                          content:content
                                                                          trigger:trigger];

    // 添加请求到通知中心
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (error) {
            NSLog(@"添加通知请求失败: %@", error.localizedDescription);
        }
    }];
}

/*
 0x00：电量低，
 0x01：电量耗尽，
 0x02：指纹连续错误，
 0x08：防撬，
 0x09：超时未关门，
 0x0A：高温报警
*/
+(NSArray *)warnStrWith:(NSInteger)warnType{
    NSString *titleStr = @"";
    NSString *descStr = @"";
    if (warnType == 0) {
        titleStr = kLocalString(@"LOW BATTERY");
        descStr = kLocalString(@"Warning.");
    }else if (warnType == 1){
        titleStr = kLocalString(@"BATTERY DRAINED");
        descStr = kLocalString(@"Warning.");
    }else if (warnType == 2){
        titleStr = kLocalString(@"ACCESS ATTEMPT");
        descStr = kLocalString(@"Warning.");
    }else if (warnType == 8){
        titleStr = kLocalString(@"STRONG IMPACT");
        descStr = kLocalString(@"Warning.");
//        descStr = kLocalString(@"Active safety protection.");
    }else if (warnType == 10){
        titleStr = kLocalString(@"HI-TEMPERATURE");
        descStr = kLocalString(@"Warning.");
//        descStr = kLocalString(@"Active safety protection.");
    }else{
        titleStr = kLocalString(@"UNKNOWN WARN");
        descStr = kLocalString(@"Warning.");
//        descStr = kLocalString(@"Active safety protection.");
    }
    return @[titleStr,descStr];
}

//远程开锁逻辑封装
+(void)remoteOpenLockAction:(void(^)(BOOL isSuccess,NSString *message))finish{
    SLUnlockAlertView *alert = [SLUnlockAlertView viewFromXIB];
    alert.style = 2;
    alert.model = kCurClickDevice;
    alert.tag = 110;
    [kAppWindow addSubview:alert];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert removeFromSuperview];
        NSDictionary *params = @{@"deviceNo":kCurClickDevice.bridgeDeviceNo,
                                 @"lockType":@(1),
                                 @"conId":@([kSTRING(kCurClickDevice.conId) integerValue]),
                                 @"memberId":@([kSTRING(kCurClickDevice.memberId) integerValue]),
                                 @"timeout":@(8),
                                 @"conTimeOut":@(8)};
        
        [ZKHttpManager postWithPath:@"/msl_user/remoteCmd" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            BOOL isOpenSuccess = [kSTRING(result[@"result"][@"status"]) isEqualToString:@"0"];
            NSString *msg = kSTRING(result[@"result"][@"message"]);
            if (!isOpenSuccess) {
                kShowToast(msg);
                if (finish) finish(NO,@"");
                return;
            }
            if (finish) finish(YES,@"");
           
        }];
    });
}

//蓝牙开锁逻辑封装
+(void)openLockAction:(void(^)(BOOL isSuccess,NSString *message))finish{
    SLUnlockAlertView *alert = [SLUnlockAlertView viewFromXIB];
    alert.style = 1;
    alert.model = kCurClickDevice;
    alert.tag = 110;
    [kAppWindow addSubview:alert];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert removeFromSuperview];
        if (kCurClickDevice.isGuest) {
            if ([kCurClickDevice.status isEqualToString:@"0"]) {
                if (finish) finish(NO,kLocalString(@"The key is disable now"));
                return;
            }
            if (![ZCTool checkGuestTime]) {
                if (finish) finish(NO,kLocalString(@"You cannot open the lock at the current time"));
                return;
            }
        }
        [self unlockAction:kCurClickDevice finish:finish];
    });
}

+(void)unlockAction:(SLLockModel *)model finish:(void(^)(BOOL isSuccess,NSString *message))finish{
    SLUnlockAlertView *alert = [kAppWindow viewWithTag:110];
    [alert removeFromSuperview];
    [ZCTool connectDeviceWith:model toast:kLocalString(@"Opening...") finish:^(BOOL isSuccess) {
        if (isSuccess) {
            [self sendOpenLockSegment:finish];
        }else{
            if (finish) finish(NO,kLocalString(@"Connect faild"));
        }
    }];
}

+(void)sendOpenLockSegment:(void(^)(BOOL isSuccess,NSString *message))finish{
    [[SLBluetoothManager sharedManager] openLockWith:@"1" uid:@"101" finish:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
        [ZCTool hideLoadingOnKeyWindow];
        if (isSuccess) {
            [ZKHttpManager uploadOpenLockRecord:@"1" unlockTime:nil unlockUid:@"1" unlockUame:kUserInfo.nickName unlockId:@"" deviceId:kCurDevice.deviceId finish:^(BOOL isSuccess) {
                if (finish) finish(isSuccess,kLocalString(@"Unlock successfully"));
            }];
        }else{
            if (finish) finish(NO,errorMsg);
        }
    }];
}

+(void)showWithAnimation:(UIView *)showView onView:(UIView *)onView{
    
    [onView addSubview:showView];
}

@end
